# -*- coding: utf-8 -*-
"""
购物车功能测试脚本
"""
import tkinter as tk
from tkinter import ttk, messagebox
import json
import os
import sys
from main import Product, SupermarketSystem, SupermarketGUI

class TestApp(tk.Tk):
    def __init__(self):
        super().__init__()
        self.title("购物车测试")
        self.geometry("500x300")
        
        # 创建测试框架
        frame = ttk.Frame(self, padding="20")
        frame.pack(fill=tk.BOTH, expand=True)
        
        # 创建标题
        ttk.Label(frame, text="购物车功能测试", font=("SimHei", 16, "bold")).pack(pady=10)
        
        # 创建按钮框架
        button_frame = ttk.Frame(frame)
        button_frame.pack(pady=20)
        
        # 测试按钮
        ttk.Button(button_frame, text="测试添加商品到购物车", command=self.test_add_to_cart).pack(pady=10)
        ttk.Button(button_frame, text="查看购物车状态", command=self.show_cart_status).pack(pady=10)
        ttk.Button(button_frame, text="测试update_cart_status函数", command=self.test_update_cart_status).pack(pady=10)
        
        # 状态标签
        self.status_var = tk.StringVar(value="准备就绪")
        ttk.Label(frame, textvariable=self.status_var, font=("SimHei", 10)).pack(pady=10)
        
        # 创建系统实例
        self.system = SupermarketSystem()
        
        # 输出当前商品列表
        self.log("当前商品列表:")
        unique_products = {}
        for product in self.system.products.values():
            unique_products[product.product_id] = product
        
        for pid, product in unique_products.items():
            self.log(f"- {product.name} (ID: {product.product_id}, 价格: ￥{product.price:.2f})")
    
    def log(self, message):
        """显示日志信息"""
        current = self.status_var.get()
        self.status_var.set(current + "\n" + message)
        print(message)
    
    def test_add_to_cart(self):
        """测试添加商品到购物车"""
        # 获取第一个商品
        unique_products = {}
        for product in self.system.products.values():
            unique_products[product.product_id] = product
        
        if unique_products:
            first_product_id = next(iter(unique_products.keys()))
            first_product = unique_products[first_product_id]
            
            # 添加到购物车
            if first_product_id in self.system.cart:
                self.system.cart[first_product_id][1] += 1
            else:
                self.system.cart[first_product_id] = [first_product, 1]
            
            self.log(f"已添加商品到购物车: {first_product.name} (数量: {self.system.cart[first_product_id][1]})")
            messagebox.showinfo("测试结果", f"已添加商品到购物车:\n{first_product.name}\n当前数量: {self.system.cart[first_product_id][1]}")
        else:
            self.log("错误: 没有可用的商品")
            messagebox.showerror("错误", "没有可用的商品")
    
    def show_cart_status(self):
        """查看购物车状态"""
        if not self.system.cart:
            self.log("购物车为空")
            messagebox.showinfo("购物车状态", "购物车为空")
        else:
            self.log("购物车内容:")
            cart_content = "购物车内容:\n"
            total = 0
            for product_id, (product, quantity) in self.system.cart.items():
                subtotal = product.price * quantity
                total += subtotal
                cart_content += f"- {product.name} x{quantity} - ￥{product.price:.2f} x{quantity} = ￥{subtotal:.2f}\n"
            
            cart_content += f"总计: ￥{total:.2f}"
            self.log(f"总计: ￥{total:.2f}")
            messagebox.showinfo("购物车状态", cart_content)
    
    def test_update_cart_status(self):
        """创建一个简单的窗口来测试update_cart_status函数"""
        # 创建一个临时窗口
        test_window = tk.Toplevel(self)
        test_window.title("测试update_cart_status")
        test_window.geometry("600x400")
        
        # 创建一个测试版的GUI实例（简化版）
        class TestGUI:
            def __init__(self, parent, system):
                self.system = system
                self.cart_frame = ttk.LabelFrame(parent, text="购物车状态")
                self.cart_frame.pack(fill=tk.BOTH, expand=True, pady=20)
                
                # 添加按钮来触发更新
                button_frame = ttk.Frame(parent)
                button_frame.pack(pady=10)
                
                ttk.Button(button_frame, text="添加测试商品", command=self.add_test_product).pack(side=tk.LEFT, padx=10)
                ttk.Button(button_frame, text="清空购物车", command=self.clear_cart).pack(side=tk.LEFT, padx=10)
                ttk.Button(button_frame, text="更新显示", command=self.update_cart_status).pack(side=tk.LEFT, padx=10)
                
                # 初始更新
                self.update_cart_status()
            
            def add_test_product(self):
                """添加测试商品"""
                # 获取第一个商品
                unique_products = {}
                for product in self.system.products.values():
                    unique_products[product.product_id] = product
                
                if unique_products:
                    first_product_id = next(iter(unique_products.keys()))
                    first_product = unique_products[first_product_id]
                    
                    # 添加到购物车
                    if first_product_id in self.system.cart:
                        self.system.cart[first_product_id][1] += 1
                    else:
                        self.system.cart[first_product_id] = [first_product, 1]
                    
                    self.update_cart_status()
            
            def clear_cart(self):
                """清空购物车"""
                self.system.cart = {}
                self.update_cart_status()
            
            def update_cart_status(self):
                """简化版的update_cart_status函数"""
                # 先清空购物车框架中的所有组件
                for widget in self.cart_frame.winfo_children():
                    widget.destroy()
                
                if not self.system.cart:
                    # 购物车为空时显示提示信息
                    empty_label = ttk.Label(self.cart_frame, text="购物车为空", font=("SimHei", 12))
                    empty_label.pack(pady=20)
                else:
                    # 创建一个内部框架来容纳Treeview和滚动条
                    content_frame = ttk.Frame(self.cart_frame)
                    content_frame.pack(fill=tk.BOTH, expand=True, padx=10, pady=5)
                    
                    # 创建Treeview组件显示购物车详细列表
                    columns = ("name", "price", "quantity", "subtotal")
                    tree = ttk.Treeview(content_frame, columns=columns, show="headings", height=min(10, len(self.system.cart)))
                    
                    # 设置列标题
                    tree.heading("name", text="商品名称")
                    tree.heading("price", text="单价")
                    tree.heading("quantity", text="数量")
                    tree.heading("subtotal", text="小计")
                    
                    # 设置列宽
                    tree.column("name", width=150, anchor=tk.W)
                    tree.column("price", width=80, anchor=tk.CENTER)
                    tree.column("quantity", width=80, anchor=tk.CENTER)
                    tree.column("subtotal", width=100, anchor=tk.CENTER)
                    
                    # 添加滚动条
                    scrollbar = ttk.Scrollbar(content_frame, orient=tk.VERTICAL, command=tree.yview)
                    tree.configure(yscroll=scrollbar.set)
                    
                    # 添加商品到Treeview
                    for product_id, (product, quantity) in self.system.cart.items():
                        subtotal = product.price * quantity
                        tree.insert("", tk.END, values=(product.name, f"￥{product.price:.2f}", quantity, f"￥{subtotal:.2f}"))
                    
                    # 放置Treeview和滚动条
                    tree.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
                    scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
                    
                    # 显示购物车总计
                    total = 0
                    for product, quantity in self.system.cart.values():
                        total += product.price * quantity
                    
                    total_label = ttk.Label(self.cart_frame, text=f"总计: ￥{total:.2f}", 
                                          font=("SimHei", 12, "bold"))
                    total_label.pack(pady=10, side=tk.BOTTOM, anchor=tk.E, padx=20)
        
        # 创建测试GUI
        self.test_gui = TestGUI(test_window, self.system)

if __name__ == "__main__":
    app = TestApp()
    app.mainloop()